<template>
  <div>
    <NavBar title="添加收货地址" />
    <van-address-edit
      :area-list="areaList"
      show-search-result
      detail-rows="3"
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      @save="onSave"
    />
  </div>
</template>
<script setup>
import { ref } from "vue";
import { getCitys, getCreateAddress } from "../../API";
import NavBar from "../../components/NavBar.vue";
import { useRouter } from "vue-router";
let router = useRouter();
let areaList = ref({
  province_list: {},
  city_list: {},
  county_list: {},
});
let obj = ref({
  city_code: "", //城市代码
  city_name: "", //城市名称
  default: 0,
  detail: "", //详细地址
  district_code: "", //区号
  district_name: "", //区名
  name: "",
  phone: "",
  province_code: "", //省号
  province_name: "", //省
});
const searchResult = ref([]);

const onSave = async (e) => {
  // console.log(e);
  obj.value = {
    city_code: e.areaCode, // 城市代码
    city_name: e.city, // 城市名称
    default: e.isDefault ? 1 : 0, // 是否为默认地址
    detail: e.addressDetail, // 详细地址
    district_code: e.areaCode, // 区号
    district_name: e.county, // 区名
    name: e.name,
    phone: e.tel,
    province_code: e.areaCode.slice(0, 2) + "0000", // 省号，这里只是一个示例
    province_name: e.province, // 省
  };
  // console.log(obj.value);
  const getSave = async () => {
    try {
      const { data } = await getCreateAddress(obj.value);
      console.log(data);
      router.push("/address/list");
    } catch (error) {
      console.log(error);
    }
  };

  await getSave();
};

let getCityLists = async () => {
  let { data } = await getCitys();
  // console.log(data);
  areaList.value = transformDataToAreaList(data);
  // console.log(areaList.value);
};
getCityLists();
let transformDataToAreaList = (data) => {
  // 遍历省份信息
  for (let province of data) {
    areaList.value.province_list[province.code] = province.text;

    // 遍历城市信息
    for (let city of province.children) {
      areaList.value.city_list[city.code] = city.text;

      // 遍历区/县信息
      for (let county of city.children) {
        areaList.value.county_list[county.code] = county.text;
      }
    }
  }
  return areaList.value;
};
</script>
<style scoped>
</style>